//
//  AppDelegate+FSWExtension.m
//  quhuolang_service
//
//  Created by 曹欣欣 on 2018/2/8.
//  Copyright © 2018年 fusw. All rights reserved.
//

#import "AppDelegate+FSWExtension.h"
#import "MainNavigationVC.h" 
#import "FSWGetAppInfo.h"
#import <UserNotifications/UserNotifications.h> 
#import "NotificationService.h"
#include<arpa/inet.h>
#import <UMCommonLog/UMCommonLogHeaders.h>
//#import "UMessage.h"
#import <AVFoundation/AVFoundation.h>
#define kFileManager [NSFileManager defaultManager]
@interface AppDelegate ()<AVAudioPlayerDelegate,AVSpeechSynthesizerDelegate,UIApplicationDelegate>
{
    AVSpeechSynthesizer *synthesizer;
}
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
 


//声音文件的播放器
@property (nonatomic, strong)AVAudioPlayer *myPlayer;
//声音文件的路径
@property (nonatomic, strong) NSString *filePath;

@end

@implementation AppDelegate (FSWExtension)

- (void)configIQKeyboard
{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 30;
}
-(void)getPublicParameter{
    //    self.publicParameterDict = [FSWOSAndAppInfo getOSAndAppinfo];
    //    [AppDelegate delegateApp].publicParameterDict = [FSWPublicParameter getOSAndAppinfo];
}

@end


@implementation AppDelegate (HUD)

- (void)addSVProgressHUD
{
    UIColor *black = [[UIColor blackColor] colorWithAlphaComponent:0.75];
    [SVProgressHUD setBackgroundColor:black];
    [SVProgressHUD setForegroundColor:[UIColor colorWithHexString:@"FFFFFF"]];
    [SVProgressHUD setRingThickness:4];
    [SVProgressHUD setRingNoTextRadius:12];
    [SVProgressHUD setRingRadius:12];
    [SVProgressHUD setCornerRadius:8];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setMaximumDismissTimeInterval:2];
    [SVProgressHUD setInfoImage:[UIImage imageNamed:@""]];
}

@end
 
 
@implementation AppDelegate (Network)

- (void)networkStatus
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                XCLog(@"未知网络");
                break;
            case 0:
                XCLog(@"网络不可达");
                break;
            case 1:
                XCLog(@"GPRS网络");
                break;
            case 2:
                XCLog(@"wifi网络");
                break;
            default:
                break;
        }
        if(status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi ){
        }else{
            //            [FSWToast showWithText:@"亲，网络已断开！"];
        }
    }];
}

@end

@implementation AppDelegate (ScrollViewAdjust)

- (void)scrollViewAdjust
{
    if (@available(iOS 11.0, *)){
        //避免滚动视图顶部出现20的空白以及push或者pop的时候页面有一个上移或者下移的异常动画的问题
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}

@end

@implementation AppDelegate (UMeng)
- (void)configUMeng:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    // 请求授权
        if ([UNUserNotificationCenter class] != nil) {
            // iOS 10+
            [UNUserNotificationCenter currentNotificationCenter].delegate = self;
            UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
            [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[UIApplication sharedApplication] registerForRemoteNotifications];
                    });
                } else {
                    NSLog(@"推送权限被拒绝");
                }
            }];
        }
    
    // Override point for customization after application launch.
    [UMCommonLogManager setUpUMCommonLogManager];//开启日志
    [UMConfigure setLogEnabled:YES];//设置打开日志
    //设置从push后端申请的appkey
    [UMConfigure initWithAppkey:@"669e737c03f2687ab24ad9c1" channel:@"App Store"];
    
    // Push组件基本功能配置
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    [UNUserNotificationCenter currentNotificationCenter].delegate=self;
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            
        }else{
        }
    }];
}
-(void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
     if(![deviceToken isKindOfClass:[NSData class]])return;
    const unsigned * tokenBytes =(const unsigned*)[deviceToken bytes];
    NSString * hexToken =[NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    NSLog(@"deviceToken:%@",hexToken);
    //1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    //传入的devicetoken是系统回调didRegisterForRemoteNotificationsWithDeviceToken的入参，切记
    [UMessage registerDeviceToken:deviceToken];
    
}
 
//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification*)notification withCompletionHandler:(void(^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary* userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
//      [self playSound:userInfo];
        [self speakText:@"收款5688.9元"];
    }else{
        //应用处于前台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionAlert);
}
 
//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse*)response withCompletionHandler:(void(^)(void))completionHandler{
    NSDictionary* userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
         //应用处于后台时的本地推送接受
    }
}
  
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    XCLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    //应用处于后台时的本地推送接受
}

//语音播报
- (void)speakText:(NSString *)text {
    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
    utterance.rate = 0.5; // 语速，可以根据需要调整
    utterance.pitchMultiplier = 1.2; // 音调，同样可以根据需要调整
//    utterance.volume = 0.8; // 设置音量为最大音量的80%
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"]; // 设置语言
    [self.synthesizer speakUtterance:utterance]; // 开始TTS
}
//播放剩余
-(void)playSound:(NSDictionary *)userInfo{
    NSDictionary *extras =  [userInfo objectForKey:@"aps"] ;
    NSString *sound = [extras objectForKey:@"sound"];
    if([sound isEqualToString:@"jpush_order_sound.wav"]){
        NSString *amount = @"1000" ;//10000
        NSArray *musicArr = [[XSAudioManager sharedInstance] getMusicArrayWithNum:amount];
        __weak __typeof(self)weakSelf = self;
        [[XSAudioManager sharedInstance] pushLocalNotificationToApp:0 withArray:musicArr completed:^{
            // 播放完成后，通知系统
    //        weakSelf.contentHandler(weakSelf.bestAttemptContent);
        }];
    }
    
}
 
-(NSInteger)isSound{
    NSString *sound = [fUserDefaults objectForKey:NOTICFICATION_SOUND];
//    sound 0开 1关
//    if ([FSWHelperTool isBlankString:sound]) {
        sound = @"0";
//    }
    return [sound integerValue];
}
 

@end
 
@implementation AppDelegate (AppInfo)

- (UIViewController *)instantiateViewControllerWithStoryboardName:(NSString *)storyboardName identifier:(NSString *)identifier
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:identifier];
    return (BaseViewController *)viewController;
}
- (void)getAppInfo
{
    [FSWGetAppInfo getAppInfo];
}
@end

@implementation AppDelegate (AVSpeech)
 
- (void)speechSynthesizerDidStartSpeechUtterance:(AVSpeechSynthesizer *)synthesizer {
    // 开始说话的回调
}
  
- (void)speechSynthesizerDidFinishSpeechUtterance:(AVSpeechSynthesizer *)synthesizer {
    // 结束说话的回调
}
  
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtteranceWithError:(nullable NSError *)error {
    // 说话过程中发生错误的回调
    if (error != nil) {
        NSLog(@"Error: %@", error.localizedDescription);
    }
}

@end

 
